<?php
declare (strict_types = 1);

namespace app\mobile\controller;

use think\facade\Db;
use think\facade\Session;
use think\facade\Cache;
use think\facade\Config;
use think\facade\View;
use think\facade\Env;
use think\facade\Request;
class Base extends \app\mobile\Base
{
  public $md, $con, $ac, $appPath,$cli,$header;
  public $menu, $app, $guid,$develop,$system,$sysbase;
  public $user,$mid,$uid,$openid,$member;
  public $appPlatform;

  public function initialize()
  {
    
    $request = request();
    $method = Request::method();
    if ($method == 'OPTIONS') {
      exit();
    }

    $this->md = app('http')->getName();
    $this->con = $request->controller();
    $this->ac = $request->action();

    $this->header = Request::header();

    if (isset($this->header['token'])) {
      $this->token = $this->header['token'];
      if ($this->token) {
        $this->user = Db::name('user')
                ->where('token',$this->token)
                ->find();
        if ($this->user) {
          // unset($this->user['token'])
          $this->uid = $this->user['id'];
        }
      }
    }

    if (input('appPlatform')) {
      $this->appPlatform = input('appPlatform');
    }
    $this->sysbase = getSettingGroup('base');
  }

  public function uploc()
  {
    # code...
  }
  public function remove()
  {
    $id = input('id');
    $ret = Db::name($this->con)->whereIn('id',$id)->delete();
    if ($ret) {
      # code...
    }
    return $this->doSuccess('ok');
  }

  public function updateBat()
  {
    $forms = input('form');
    foreach ($forms as $form) {
      $rows = Db::name($this->con)
              ->where('id',$id)
              ->update($form);
    }
    return $this->doSuccess('ok');
  }

  public function index()
  {
    return View::fetch();
  }

  public function uppic()
  {
    $image = request()->file('file');
    $type = input('type');
    try {
      validate(
        [
          'file' => 
          [
            'fileExt' => 'gif,jpg,png'
          ]
        ]
      )->check(['file' => $image]);
      
      $savename = \think\facade\Filesystem::putFile( 'public', $image);
      $url = Request::domain()."/upload/".$savename;

      return $this->doSuccess('ok',$url);
    } catch (\think\exception\ValidateException $e) {
      return $this->doError('ok',$e->getMessage());
    }
  }

  public function add()
  {
    return View::fetch();
  }

  public function doError($msg = '')
  {
    $resp['code'] = 400;
    $resp['msg'] = $msg;
    $json = json($resp, 200);
    return $json;
  }

  public function doSuccess($msg = '', $data = '')
  {
    $resp['code'] = 200;
    $resp['msg'] = $msg;
    $resp['data'] = $data;
    $json = json($resp, 200);
    return $json;
  }
}
